from django import forms
from rbac import models
from django.core.exceptions import ValidationError
from django.conf import settings
from rbac.service.init_permission import init_permission


class login_form(forms.Form):
    name = forms.CharField(max_length=64)
    password = forms.CharField(max_length=64)

    def __init__(self, request, *args, **kwargs):
        super(login_form, self).__init__(*args, **kwargs)
        self.request = request

    def clean(self):
        # 通过前端获取的账号密码 校验当前用户是否存在
        name = self.request.POST.get('name')
        password = self.request.POST.get('password')
        user_obj = models.UserInfo.objects.filter(name=name, password=password).first()
        if user_obj:
            init_permission(request=self.request, user=user_obj)
            # 存用户信息
            self.request.session[settings.USER_INFO] = {'id': user_obj.id, 'name': user_obj.name}
            return self.cleaned_data
        else:
            # raise ValidationError('账号或密码错误，多次输入错误无法登入，请联系所在部门负责人')
            self.add_error('password', '账号或密码错误，若多次输入无法登入，请联系所在部门负责人')
